<template>
  <view class="article-add-page">
    <uni-page-header title="发贴" />
    <view class="main-container">
      <view class="header">
        <view class="label">
          <u-icon name="file-text" color="#999" size="18" />
          <text class="value">将发布到此话题</text>
        </view>
        <view class="topic">{{ topicDetail.name }}</view>
      </view>
      <view class="form-container">
        <u-upload
          name="article_img" 
          accept="image"
          :file-list="imgList"
          upload-text="最少上传3张"
          @afterRead="onAfterRead"
          @delete="onImgDelete"
        />

        <u--textarea
          v-model="formData.name"
          count
          auto-height
          maxlength="20"
          border="bottom"
          placeholder="填写标题, 更容易获得大家的讨论"
        />

        <u--textarea
          v-model="formData.content"
          count
          height="300"
          maxlength="1000"
          border="bottom"
          placeholder="请输入内容"
        />
        <view class="address" @click="chooseLocation">
          <u-icon name="map" color="#999" size="18" />
          <view class="value">{{ formData.address }}</view>
        </view>
      </view>
    </view>

    <view class="action-btn">
      <u-button color="#78ffe6" text="发布" shape="circle" :loading="submitLoading" @click="onSubmit" />
    </view>
  </view>
</template>

<script>
import {
  mapState
} from 'vuex'
import {
  getImg,
  uploadFile,
  chooseLocation
} from '../utils/index.js'
import {
  wx_talk_subject_post_add
} from '../api/index.js'
export default {
  name: 'ArticleAdd',
  data() {
    return {
      imgList: [],
      formData: {
        subject_id: '', // 话题ID
        image: '',
        name: '',
        content: '',
        location: '', // 地理位置
        address: '', // 详细地址
        longitude: '', // 经度
        latitude: '' // 纬度
      },
      submitLoading: false,
      locationRes: null
    }
  },
  computed: {
    ...mapState(['topicDetail'])
  },
  onLoad(params) {
    // this.judegAuthor()

    // uni.chooseLocation({
    //   success: function(res) {
    //     console.log('位置信息')
    //     console.log(res)
    //   }
    // })
  },
  methods: {
    chooseLocation() {
      chooseLocation().then(res => {
        this.locationRes = res
        this.formData.location = res.name
        this.formData.address = res.address
        this.formData.longitude = res.longitude
        this.formData.latitude = res.latitude
      })
    },
    judegAuthor() {
      const _this = this
      uni.getSetting({
        success: res => {
          console.log('已授权的用户权限')
          console.log(res)
          // 定位权限已授权，则直接获取位置信息
          if (res.authSetting['scope.userLocation']) {
            _this.getLocation()
          } else {
            // 否则提示用户授权
            uni.authorize({
              scope: 'scope.userLocation',
              success: () => {
                console.log('确认授权')
                _this.getLocation()
              }
            })
          }
        }
      })
    },
    getLocation() {
      console.log('开始获取定位信息')
      uni.getLocation({
        type: 'wgs84',
        success: res => {
          console.log('位置信息')
          console.log(res)
        },
        complete: res => {
          console.log('定位方法执行结束')
          console.log(res)
        }
      })
    },

    async onAfterRead(data) {
      const _this = this
      console.log('图片选择结果')
      console.log(data)
      const {
        size,
        url,
        type
      } = data.file
      const uploadRes = await uploadFile(url, size, {
        filetype: url,
        name: 'file'
      })
      console.log('图片上传结果')
      console.log(uploadRes)
      const linkUrl = getImg({
        i: uploadRes.fileid,
        n: 'topic-img'
      })
      console.log('上传后的服务器图片链接')
      console.log(linkUrl)
      this.imgList.push({
        i: uploadRes.fileid,
        n: 'topic-img',
        t: 0,
        url: linkUrl
      })
    },

    onImgDelete(data) {
      const {
        index
      } = data
      this.imgList.splice(index, 1)
    },

    async onSubmit() {
      if (this.imgList.length === 0) {
        this.$utils.showToast('请上传图片')
        return
      } 
      if (this.imgList.length < 3) {
        this.$utils.showToast('最少添加3张图片')
        return
      }
      const {
        title,
        content,
        address
      } = this.formData
      if (title === '') {
        this.$utils.showToast('请填写帖子标题')
        return
      }
      if (content === '') {
        this.$utils.showToast('请填写帖子内容')
        return
      }
      if (address === '') {
        this.$utils.showToast('请选择定位')
        return
      }
      this.formData.image = JSON.stringify(this.imgList.map(e => {
        const {
          i,
          n,
          t
        } = e
        return {
          i,
          n,
          t
        }
      }))
      this.formData.subject_id = this.topicDetail.id
      console.log('this.formData')
      console.log(this.formData)
      try {
        this.submitLoading = true
        await wx_talk_subject_post_add(this.formData)
        this.$utils.showToast('发布成功')
        this.submitLoading = false
        uni.$emit('article-add-success', {
          data: 1
        })
        this.$utils.switchTabToPage('/pages/diary')
      } catch (error) {
        this.submitLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .article-add-page {
    .main-container {
      padding-bottom: 20rpx;

      .header {
        height: 70rpx;
        padding: 0 20rpx;
        @include flex-between;
        background-color: #FFF;
        border-bottom: 1px solid #e6e6e6;

        .label {
          @include flex-column-center;
          gap: 5rpx;
          font-size: 28rpx;
          color: #999;
        }

        .topic {
          font-size: 28rpx;
          width: 40%;
          @include text-ellipsis;
        }
      }

      .form-container {
        width: 97%;
        margin: 20rpx auto;
        padding: 15rpx;
        background-color: #FFF;
        border-radius: 10rpx;

        .address {
          padding: 20rpx 0;
          font-size: 28rpx;
          color: #999;
          display: flex;
          gap: 10rpx;
          align-items: flex-start;

          .value {
            flex: 1;
          }
        }
      }
    }

    ::v-deep.u-upload__button {
      border-radius: 10rpx;
      background-color: #e6e6e6;
    }

    ::v-deep.u-textarea {
      padding-bottom: 40rpx;
    }
  }

  ::v-deep.action-btn {
    width: 100%;
    @include flex-center;
    position: fixed;
    bottom: 100rpx;
    left: 50%;
    transform: translateX(-50%);

    button {
      width: 60%;
      color: #000 !important;
      font-weight: bolder;
    }
  }
</style>
